package impl

import (
	"context"

	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/role"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 创建角色
func (i *impl) CreateRole(ctx context.Context, in *role.CreateRoleRequest) (
	*role.Role, error) {
	ins := role.New(in)

	_, err := i.col.InsertOne(ctx, ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

// 查询角色列表
func (i *impl) QueryRole(ctx context.Context, in *role.QueryRoleRequest) (
	*role.RoleSet, error) {
	set := role.NewRoleSet()

	// 构造查询条件
	filter := bson.M{}

	if len(in.RoleIds) > 0 {
		// IN
		filter["_id"] = bson.M{"$in": in.RoleIds}
	}

	opts := &options.FindOptions{}
	opts.SetLimit(int64(in.Page.PageSize))
	opts.SetSkip(in.Page.ComputeOffset())

	cursor, err := i.col.Find(ctx, filter, opts)
	if err != nil {
		return nil, err
	}

	// 执行查询SQL
	for cursor.Next(ctx) {
		ins := role.NewDefaultRole()
		if err := cursor.Decode(ins); err != nil {
			return nil, err
		}
		set.Add(ins)
	}

	// 统计总数
	set.Total, err = i.col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}
	return set, nil
}
